document.addEventListener('DOMContentLoaded', function() {
    const searchId = document.getElementById('searchId');
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    const clearBtn = document.getElementById('clearBtn');
    const loadingIndicator = document.getElementById('loadingIndicator');
    const audioList = document.getElementById('audioList');
    const audioTemplate = document.getElementById('audioItemTemplate');
    const errorMessage = document.getElementById('errorMessage');

    searchBtn.addEventListener('click', handleSearch);
    clearBtn.addEventListener('click', handleClear);

    function handleClear() {
        searchId.value = '';
        searchInput.value = '';
        audioList.style.display = 'none';
        audioList.innerHTML = '';
        errorMessage.style.display = 'none';
    }

    function createAudioElement(filename) {
        if (!filename) {
            console.error('Filename is undefined or empty');
            return null;
        }

        const template = audioTemplate.content.cloneNode(true);
        const audioItem = template.querySelector('.audio-item');
        const filenameDiv = audioItem.querySelector('.filename');
        const audio = audioItem.querySelector('audio');
        const downloadBtn = audioItem.querySelector('.download-btn');

        const audioUrl = `/audio/${filename}`;
        filenameDiv.textContent = `文件名：${filename}`;
        audio.src = audioUrl;
        downloadBtn.href = audioUrl;
        downloadBtn.download = filename;
        downloadBtn.textContent = '下载音频';

        return audioItem;
    }

    async function handleSearch() {
        const id = searchId.value.trim();
        const searchText = searchInput.value.trim();

        if (!id && !searchText) {
            alert('请输入 ID 或搜索内容');
            return;
        }

        // 显示加载动画
        loadingIndicator.style.display = 'block';
        audioList.style.display = 'none';
        audioList.innerHTML = '';
        errorMessage.style.display = 'none';

        try {
            const response = await fetch('/search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    id: id,
                    query: searchText
                })
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || '搜索请求失败');
            }

            const data = await response.json();
            // console.log('Server response:', data);

            if (data.status === 'success') {
                // 处理单个文件或多个文件的情况
                const files = data.files || (data.filename ? [data.filename] : []);
                // console.log('Files to process:', files);

                if (files.length === 0) {
                    throw new Error('没有收到有效的文件名');
                }

                files.forEach(filename => {
                    const audioItem = createAudioElement(filename);
                    if (audioItem) {
                        audioList.appendChild(audioItem);
                    }
                });
                audioList.style.display = 'block';
                errorMessage.style.display = 'none';
            } else if (data.status === 'not_found') {
                errorMessage.textContent = data.message || '未找到相关音频数据';
                errorMessage.style.display = 'block';
                audioList.style.display = 'none';
            } else {
                throw new Error(data.message || '处理失败');
            }
        } catch (error) {
            console.error('Error:', error);
            errorMessage.textContent = error.message;
            errorMessage.style.display = 'block';
            audioList.style.display = 'none';
        } finally {
            loadingIndicator.style.display = 'none';
        }
    }
});
